package cn.kgc.jdbc.dao;

import cn.kgc.jdbc.entity.User;
import cn.kgc.jdbc.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: mosin
 * @version: v1.0  2022/4/19
 * 用户数据的持久化操作
 */
public class UserDao {

    public User selectUser(String userName ,String pwd){
        //根据用户名 密码 完成用户的查询
        User usr  = null;
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement pstmt = null;
        String sql = "select * from usr where uname = ? and pwd = ?";
        try {
           pstmt = connection.prepareStatement(sql);
           pstmt.setString(1, userName);
           pstmt.setString(2, pwd);
           ResultSet resultSet = pstmt.executeQuery();

           while (resultSet.next()){

               int id = resultSet.getInt("id");
               String uname = resultSet.getString("uname");
               String pd = resultSet.getString("pwd");
               usr = new User(id, userName, pd);
           }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.closeAll(null, pstmt, connection);
        }
        return  usr;
    };
    //注册
    public int addUser(String userName ,String pwd){

        PreparedStatement preparedStatement = null;
        int line = 0;
        Connection connection = JDBCUtil.getConnection();
        String sql = "insert into usr (uname,pwd)values(?,?)";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, pwd);
            line = preparedStatement.executeUpdate();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.closeAll(null, preparedStatement, connection);
        }

        return line;
    }
}
